package com.cat.dynamicPlanning;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/longest-valid-parentheses/
 * @create 2025/8/27 10:30
 * @since JDK17
 */

public class Solution08 {
    public int longestValidParentheses(String str) {
        char[] s = str.toCharArray();
        int n = s.length, ans = 0;
        int[] dp = new int[n];
        for (int i = 1, p; i < n; i++) {
            if (s[i] == ')') {
                p = i - dp[i - 1] - 1;
                if (p >= 0 && s[p] == '(') {
                    dp[i] = dp[i - 1] + 2 + (p > 0 ? dp[p - 1] : 0);
                }
            }
            ans = Math.max(ans, dp[i]);
        }

        return ans;
    }
}
